/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "osObjects.h"                                          // RTOS object definitions
#include "DUGSIImaster.h" 
#include "pincfg.h"
#include "app_interface.h"

mb_baud_tab_create;

uint16_t DataRecevie[64];

uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

volatile uint32_t dgs_err;
volatile uint32_t dgs_ok;

void dgus_callback(uint8_t CmdSite, uint8_t ErrSt)
{
    if(ErrSt)
    {
        dgs_err++;
    }
    else
    {
       dgs_ok++; 
    }    
}

/*****************************************************************************//*!
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/   
void modbus_task (void const *argument)
{
    mb00_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_9600], MB_PAR_EVEN);
    mb.obj00.SlaveId=1;  
    
    mb01_Init(MB_RTU_MASTER, mb_baud_tab[MB_BAUD_9600], MB_PAR_EVEN);
    mb.obj01.SlaveId=2;
    
    mb02_Init(MB_RTU_SLAVE, 115200, MB_PAR_EVEN);
    mb.obj02.SlaveId=3;
    
    mb03_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_9600], MB_PAR_EVEN);
    mb.obj03.SlaveId=4;
    
    mb04_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_9600], MB_PAR_EVEN);
    mb.obj04.SlaveId=5;  

    
    mb05_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_9600], MB_PAR_EVEN);
    mb.obj05.SlaveId=6;   
    
    mb07_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_EVEN);
    mb.obj07.SlaveId=8;

    //mb06_Init(MB_RTU_SLAVE, mb_baud_tab[MB_BAUD_115200], MB_PAR_EVEN);
    //mb.obj06.SlaveId=8;
    

    mbapi->mmb_stc_cmd_req(&mb.obj01,1,4,FUN_CODE_READ_INPUT,&DataRecevie[0],0,16,dgus_callback);
    mbapi->mmb_stc_cmd_req(&mb.obj01,2,4,FUN_CODE_READ_INPUT,&DataRecevie[16],0x20,16,dgus_callback);
    /*
    mbStaticCmdSet(&mbxObj,0,0,FUN_CODE_DUGSII_REG_READ,DataRecevie,0x78,16,dgus_callback);
    mbStaticCmdSet(&mbxObj,3,0,FUN_CODE_DUGSII_REG_WRITE,DataSend,0x78,16,dgus_callback);
    */

    for(;;){
        osDelay(ms_ticks(20));
        
        NOP1();
        NOP1();
        mbapi->mb_poll(&mb.obj00);
        mbapi->mb_poll(&mb.obj01);
        //mbapi->mb_poll(&mb.obj02);
        mbapi->mb_poll(&mb.obj03);
        mbapi->mb_poll(&mb.obj04);
        //mbapi->mb_poll(&mb.obj05);
        //sysapi->mbapi->mb_poll(&mb06_Obj);
        //mbapi->mb_poll(&mb.obj07);
        
        //DUGSII_MasterPoll(&mbxObj);
    }
}


void mbTestCallBack(uint8_t CmdSite, uint8_t ErrSt){
    if(ErrSt)
        mbTestErrCnt++; 
    else
        mbTestOkCnt++;
}

